<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>单文件上传</span>
        </div>
      </template>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="名字">
          <el-input v-model="formInline.user" placeholder="请输入名字" clearable />
        </el-form-item>
        <el-form-item label="文件上传">
          <el-upload v-model:file-list="fileList" class="upload-demo" action="" :limit="2" :before-upload="beforeUpload"
            :on-exceed="onExceed" :http-request="uploadFile" :on-remove="onRemove" multiple>
            <el-button type="primary">上传文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                jpg/png files with a size less than 500KB.
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="submit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang='ts' name="danwj">
import axios from '../http/index.ts'
import { reactive, ref } from 'vue';
import { ElMessage, ElNotification } from 'element-plus'
const formInline = reactive({
  user: '',
  file: '',
})
const fileList = ref([{
  name: '全家桶kfc',
  url: '../../src/assets/logo.png'
}])
const uploadFile = (v: any) => {
  formInline.file = v.file
}

// 超出限制的提示
const onExceed = () => {
  ElMessage.warning('你也超出最大文件数！')
}
const submit = async () => {
  let formdate = new FormData()
  formdate.append('user', formInline.user)
  formdate.append('file', formInline.file)
  // axios
  let { data } = await axios.post('/upload/create', formdate, {
    headers: { 'Content-type': 'multipart/form-data' }
  })
  if (data?.code === 2000) {
    ElNotification({
      title: '上传成功！',
      duration: 2000
    })
  } else {
    ElNotification({
      title: '上传失败！',
      duration: 2000
    })
  }
}
const beforeUpload = (file: any) => {
  const isJPG = file.type === 'image/ipg'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) {
    ElMessage.warning('上传的照片只能是jpg！')
  }
  if (!isLt2M) {
    ElMessage.warning('上传的照片只能是小于2M')
  }
}

</script>

<style scoped lang='scss'>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>